﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace WorkStation.Frameworks.Core.Util
{
    /// <summary>
    /// * 枚举辅助类
    /// </summary>
    /// <typeparam name="TEnum">枚举类型</typeparam>
    public class EnumUtil<TEnum>
    {
        protected static List<EnumEntity> _CACHE;

        /// <summary>
        /// * 根据枚举名称得到枚举
        /// </summary>
        /// <param name="name">枚举名称</param>
        /// <returns></returns>
        public static TEnum GetEnumByName(string name)
        {
            return (TEnum)Enum.Parse(typeof(TEnum), name);
        }

        /// <summary>
        /// * 根据枚举值得到枚举
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns></returns>
        public static TEnum GetEnumByValue(int value)
        {
            string name = Enum.GetName(typeof(TEnum), value);

            return GetEnumByName(name);
        }

        /// <summary>
        /// * 获得枚举信息
        /// </summary>
        /// <returns></returns>
        public static List<EnumEntity> GetEnumInfo()
        {
            List<EnumEntity> res = new List<EnumEntity>();

            Type type = typeof(TEnum);

            if (EnumUtil<TEnum>._CACHE != null)
            {
                return EnumUtil<TEnum>._CACHE;
            }

            FieldInfo[] fields = type.GetFields();

            bool isFirst = true;

            foreach (FieldInfo field in fields)
            {
                if (isFirst)
                {
                    isFirst = false;
                    continue;
                }

                EnumEntity entity = new EnumEntity()
                {
                    EnumText = field.Name,
                    EnumValue = Convert.ToInt32(Enum.Parse(type, field.Name))
                };

                var descAttribute = field.GetCustomAttributes(false).FirstOrDefault(v => v.GetType().Name.Equals("DescriptionAttribute"));

                if (descAttribute != null)
                {
                    entity.EnumDesc = (descAttribute as DescriptionAttribute).Description;
                }

                res.Add(entity);
            }

            EnumUtil<TEnum>._CACHE = res;

            return res;
        }
    }

    /// <summary>
    /// * 枚举信息实体
    /// </summary>
    [Serializable]
    public class EnumEntity
    {
        /// <summary>
        /// * 枚举值名称
        /// </summary>
        public string EnumText { get; set; }

        /// <summary>
        /// * 枚举值
        /// </summary>
        public int EnumValue { get; set; }

        /// <summary>
        /// * 枚举描述【需要在枚举上标注Description标记】
        /// </summary>
        public string EnumDesc { get; set; }
    }
}
